package com.ihrm.company.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.mapper.DepartmentMapper;
import com.ihrm.domain.company.Department;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DepartmentService extends BaseService<Department> {

	@Autowired
	private DepartmentMapper departmentMapper;

	@Autowired
	private IdWorker idWorker;
	/**
	 * 1.保存部门
	 */
	public void save(Department department){
		//设置主键值
		String id = idWorker.nextId() + "";
		department.setId(id);
		//调用mapper保存部门
		departmentMapper.save(department);

	}


	/**
	 * 2.根据id更新部门
	 */
	public void update(Department department){
		//1.根据id查询部门
		Department deptDb = departmentMapper.findById(department.getId()).get();
		//2.修改部门属性，更新
		deptDb.setName(department.getName());
		deptDb.setCode(department.getCode());
		deptDb.setIntroduce(department.getIntroduce());
		departmentMapper.save(deptDb);
	}

	/**
	 * 3.根据id查询部门
	 */
	public Department findById(String id){
		return departmentMapper.findById(id).get();
	}

	/**
	 * 4.查询企业下的全部部门列表
	 */
	public List<Department> findAll(String companyId){
/*
		Specification<Department> spec = new Specification<Department>() {
			*/
/**
			 * 类似MyBatisPlus
			 * 用户构造查询条件，将查询条件转换为谓词表达式
			 * 1.只查询companyId
			 * 2.很多的地方都需要根据companyId查询
			 * 3.很多对象都具有companyId属性
			 * 抽取Specification方法
			 *
			 * @param root 根对象，表示查询的实体类型为Department
			 *        cq  : CriteriaQuery对象，包含查询的元数据,一般不用
			 * @param query 查询对象，包含查询的元数据
			 * @param cb CriteriaBuilder对象，用于构建查询条件
			 * @return Predicate 谓词表达式，用于过滤companyId等于指定值的部门
			 *//*


			@Override
			public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//根据企业id查询
				return cb.equal(root.get("companyId").as(String.class),companyId);
			}

		};
*/

		return departmentMapper.findAll(getSpec(companyId));
	}

	/**
	 * 5.根据id删除部门
	 */
	public void deleteById(String id){
		departmentMapper.deleteById(id);
	}
}
